<?php
namespace Home\Controller;
use Think\Controller;
class JieController extends CommonController {
	public function index()
	{	
		//echo U('home/jie/index',array('id'=>22));exit;
		// /yuephp/bbs1/index.php/home/jie/index/id/22.html
		$id = I('get.id');

		//取出问题的数据 二维数组
		$sql = "select t1.*,t2.nickname,t2.face from question t1 inner join user t2 on t1.uid=t2.id where t1.id='{$id}'";

		$res = M()->query($sql);
		//var_dump($res);exit;
		$question = current($res);
		
		//添加浏览量 继承Controller可直接$this,增加问题表$table,的浏览量(字段filed),"每次刷新浏览+1(num)",$di(查询到的自增id通过get传过来的);
		$this->autoAdd('question','view_num','+1',$id);

		$this->getTopView();  //执行最近热帖方法在页面显示10条热帖，在首页也需要执行此方法
		$this->getTopAnswer(); //执行最近热议方法在页面显示10条热议，在首页也需要执行此方法

		//链接表：问题表uid14=用户表id14 条件 问题表的qid=当前get过来的$id 取出回答当前问题的(回复)及用户表的名字、头像
		$sql = "select t1.*,t2.nickname,t2.face from answer t1 inner join user t2 on t1.uid=t2.id where t1.qid='{$id}'";
		$answers = M()->query($sql);		
		//var_dump($answers);

		$this->assign('answers',$answers);

		//$question = M('question')->find($id);//根据用户发布问题get里的id查询出一条数据
		//取了不同的问题'$question'
		$this->assign('question',$question);

		//分配动态的title，对应的是每个问题的问题名$question['title']
		$this->assign('title',$question['title']);

		$this->display();
	}

    public function add(){
    	//select拿出所有数据
    	//$cates = M('category')->select();
    	$cates = D('category')->getCate();

    	$this->assign('cates',$cates);
    	//var_dump($cates);
    	
        /*链接数据库verify  D实例化模型*/
        $question = D('verify')->getOneVerify();
       
        $this->assign('title','发表新贴'); //分配动态的title，对应的是'发表新贴'

        $this->assign('question',$question);

        $this->display();
    }

    //异步执行发布帖子的方法
    public function ajaxAdd()
    {
    	//var_dump($_POST);
    	
    	$verify = I('post.verify');
    	if ($verify!= $_SESSION['answer']) {
    		$arr = array(
    			'error'=>1,
    			'info'=>'人类验证失败',
    		);
    		echo json_encode($arr);
    		exit;
    	}

    	//$this->autoAdd('user','kiss',-20);

    	$data = I('post.');
    	$data['uid'] = $_SESSION['id'];
    	$data['create_time'] = time();

    	//添加完数据可以拿到自增id，供get使用
    	if($id = M('question')->add($data)){

    		$arr = array(
    			'error'=>0,
    			'info'=>'发布成功',
    			//发布成功用U方法生成路径，array传参id=$id参数，异步成功后resones.url可使用url里的路径
    			'url'=>U('home/jie/index',array('id'=>$id))
    		);
    		echo json_encode($arr);
    		exit;
    	}else{
    		$arr = array(
    			'error'=>1,
    			'info'=>'发布失败',
    		);
    		echo json_encode($arr);
    		exit;
    	}

    }

    public function uploadImage()
    {
    	//var_dump($_FILES);
    	$upload = new \Think\Upload();// 实例化上传类
	    $upload->maxSize   =     3145728 ;// 设置附件上传大小
	    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	    $upload->rootPath  =     './Pic/'; // 设置附件上传根目录
	    $upload->savePath  =     ''; // 设置附件上传（子）目录
	    // 上传文件 
	    $info   =   $upload->upload();

	    // var_dump($info);

	    if(!$info) {// 上传错误提示错误信息
	        echo $upload->getError();
	    }else{// 上传成功
	    	$info = current($info);
	    	$path = __ROOT__."/Pic/".$info['savepath'].$info['savename'];

	    	$arr = array(
	    		'code'=>0,
	    		'msg'=>'成功',
	    		'data'=>array(
	    			'src'=>$path,
	    			'title'=>'图片',
	    			)
	    		);
	    	echo json_encode($arr);
	    	/*{
		    	"code":0//0表示成功，其他失败
		    	,"msg":""//提示信息 一般上传失败后返回
		    	,"data":{
		    		"src":"图片路径"
		    		,"title":"图片名称"//可选
		    	}
	    	}*/

	    }
    }

    //异步执行回复帖子的方法
    public function addAnswer()
    {
    	//var_dump($_POST);
    	$data = I('post.');
    	$data['uid'] = $_SESSION['id'];
    	$data['create_time'] = time();

    	if(M('answer')->add($data)){
    		$this->autoAdd('question','answer_num','+1',I('post.qid')); //回复成功时增加当前问题的回复量id=I('post.qid')异步post的隐藏qid
    		$this->autoAdd('user','answer_num','+1',$_SESSION['id']);//回复成功时给在首页的用户回答次数+1
    		$arr = array(
    			'error'=>0,
    			'info'=>'回复成功',
    		);
    		echo json_encode($arr);
    		exit;
    	}else{
    		$arr = array(
    			'error'=>1,
    			'info'=>'回复失败',
    		);
    		echo json_encode($arr);
    		exit;
    	}
    }


    //搜索
    public function So()
    {
       //var_dump($_GET);
       $q = I('get.q');
       Vendor('Pscws4.pscws4','','.class.php');
       //全局类加\
       $pscws = new \PSCWS4('utf8');
       //var_dump($pscws); 成功引入可以打印
       $pscws->set_dict('./Public/dict.utf8.xdb');
       $pscws->send_text($q);

       $tops = $pscws->get_tops(4, 'n,v');
       //var_dump($tops);
       /*array (size=3)
          0 => 
            array (size=4)
              'word' => string '得开' (length=6)
              'times' => int 1
              'weight' => float 11.340000152588
              'attr' => string 'nz�' */

       //select * from question where content like "%使用%" or content like "%风格%";
       //mysql> select name from stu where name like '%思%';

       $sql = "select * from question where";
       foreach ($tops as $row) {
           $sql .= " title like '%".$row['word']."%' or";
       }
       //var_dump($sql);
       //'select * from question where title like '%得开%' or title like '%微软%' or title like '%防盗门%' or'

       $sql = rtrim($sql,' or');
       //var_dump($sql);
       $res = M()->query($sql);
       //var_dump($res);
       //搜索什么  替换成什么  在哪里搜索
       //str_replace(search, replace, subject);
       // str_replace('小明', "<span sytle='color:red'>小明</span>", )
      
       foreach ($res as $k => $v) {
            foreach ($tops as $vv) {
                $title = str_replace($vv['word'], "<span style='color:red'>".$vv['word']."</span>",$v['title']);
                $res[$k]['title'] = $title;

            }
          
       }
       //"'".$row['title']."'", "<span style='color:red'>".$row['title']."</span>"
       var_dump($res);
       $this->assign('res',$res);
       $this->display();
    }

}

?>